package com.example.server.controller;

import com.example.server.config.security.JwtRequest;
import com.example.server.config.security.JwtResponse;
import com.example.server.config.security.JwtTokenUtil;
import com.example.server.mapper.entity.User;
import com.example.server.service.UserService;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping
public class JwtAuthenticationController {
    private final UserService userService;
    private final JwtTokenUtil jwtTokenUtil;

    public JwtAuthenticationController(UserService userService, JwtTokenUtil jwtTokenUtil) {
        this.userService = userService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @PostMapping(value = "/authenticate")
    public JwtResponse createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) {
        User user = userService.getOne(authenticationRequest.getUsername());
        if (Objects.isNull(user) || !authenticationRequest.getPassword().equals(user.getPassword())) {
            throw new BadCredentialsException("用户名或密码不正确");
        }
        String token = jwtTokenUtil.generateToken(user.getUserName());
        return new JwtResponse(token);
    }
}
